import { MessageBox } from 'element-ui'
import manager from '@/vng/manager'
import config from '@/vng/config'
import DialogUtil from '@/utils/dialog'
import { downloadFile } from '@/utils'
import Loading from '@/utils/loading'
import { parseFile, parseGraph, makeDxf } from '@/api/vng'

/*
 * 自定义命令
 */

function SimpleTest() {
  const core = manager.CurCore()
  // console.log(core)

  const nodes = [
    { id: 1, x: 175, y: 0 },
    { id: 2, x: 75, y: 100 },
    { id: 3, x: 275, y: 100 },
    { id: 4, x: 75, y: 200 },
    { id: 5, x: 275, y: 200 },
    { id: 6, x: 175, y: 300 }
  ]
  // createNetwork an array with edges
  const edges = [
    { id: 1, s: 1, t: 2 },
    { id: 2, s: 1, t: 3 },
    { id: 3, s: 2, t: 4 },
    { id: 4, s: 2, t: 5 },
    { id: 5, s: 3, t: 5 },
    { id: 6, s: 4, t: 6 },
    { id: 7, s: 5, t: 6 }
  ]
  core.createNetwork({ code: 0, nodes: nodes, edges: edges })
}

// 新建文件
function NewGraph() {
  MessageBox.confirm('确定要新建一个空的通风网络图?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      const core = manager.CurCore()
      core.resetModel()
    })
    .catch(err => {})
}

function DeleteGraph() {
  MessageBox.confirm('确定要删除一个空的通风网络图?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      const core = manager.CurCore()
      core.resetModel()
    })
    .catch(err => {})
}

function OpenGraph() {
  DialogUtil.Show('GraphOpenDialog').then(res => {
    if (res) {
      // 构造表单数据
      // res是json对象,包含自动布局的所有数据
      console.log('数据打开对话框返回:', res)
      const formData = new FormData()
      for (const key in res) {
        formData.append(key, res[key])
      }

      // 显示loading遮罩
      Loading.Show('正在解析上传数据, 请耐心等待~')
      const core = manager.CurCore()
      // ajax请求: 解析上传的json文件
      parseFile(formData)
        .then(data => {
          console.log('返回数据:', data)
          // 打开json文件
          core.readFromJson(data)
          // 关闭loading遮罩
          Loading.Close()
        })
        .catch(err => {
          // 关闭loading遮罩
          Loading.Close()
          // 弹框显示错误信息
          MessageBox.alert(err, '提示', {
            confirmButtonText: '确定',
            showClose: false
          })
        })
    }
  })
}

function SaveGraph() {
  exportJson('矿井通风网络图', 'json')
}
function ShareGraph() {
  prompt('分享到邮箱', '输入邮箱', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
    inputErrorMessage: '邮箱格式不正确'
  })
    .then(({ value }) => {
      this.$message({
        type: 'success',
        message: '你的邮箱是: ' + value
      })
    })
    .catch(() => {
      this.$message({
        type: 'info',
        message: '取消输入'
      })
    })
}

function ImportGraph() {
  DialogUtil.Show('GraphImportDialog').then(res => {
    if (res) {
      // 构造表单数据
      // res是json对象,包含自动布局的所有数据
      console.log('数据导入对话框返回:', res)
      const formData = new FormData()
      for (const key in res) {
        formData.append(key, res[key])
      }

      // 显示loading遮罩
      Loading.Show('正在解析上传数据, 请耐心等待~')
      const core = manager.CurCore()
      // ajax请求: 解析上传文件
      parseFile(formData)
        .then(data => {
          // console.log('返回数据:', data)
          // 根据计算的结果更新diagram
          core.createNetwork(data)
          // 缩放到适合的比例尺
          core.zoomFit()
          // 关闭loading遮罩
          Loading.Close()
        })
        .catch(err => {
          // 关闭loading遮罩
          Loading.Close()
          // 弹框显示错误信息
          MessageBox.alert(err, '提示', {
            confirmButtonText: '确定',
            showClose: false
          })
        })
    }
  })
}

// 图片与Base64编码之间的转换和下载
// https://blog.csdn.net/qq20004604/article/details/72824147
// https://blog.csdn.net/four_lemmo/article/details/70158844
/**
 * base64 转 blob 对象，文件上传
 * 转载自：http://blog.csdn.net/hsany330/article/details/52575459
 * @param dataURI
 * @returns {Blob}
 */
function dataURItoBlob(dataURI) {
  var byteString = atob(dataURI.split(',')[1])
  var mimeString = dataURI
    .split(',')[0]
    .split(':')[1]
    .split(';')[0]
  var ab = new ArrayBuffer(byteString.length)
  var ia = new Uint8Array(ab)
  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i)
  }
  return new Blob([ab], { type: mimeString })
}

function stringToBlob(content) {
  return new Blob([content])
}

// 生成svg图形
// 取出dom对象的html字符串源码: svg.outerHTML
function exportSvg(_scale, _filename, _type) {
  const core = manager.CurCore()
  // 生成svg
  const svg = core.exportSvg(_scale)
  console.log(svg.outerHTML)
  downloadFile(stringToBlob(svg.outerHTML), _filename, _type)
}

function exportImg(_scale, _filename, _type) {
  const core = manager.CurCore()
  // 生成jpg
  const img = core.exportImg(_type, _scale)
  // console.log(img);
  // img.src采用Base64编码表示图片
  downloadFile(dataURItoBlob(img.src), _filename, _type)
}

function exportJson(_filename, _type) {
  const core = manager.CurCore()
  const graph = core.exportJson()
  downloadFile(stringToBlob(JSON.stringify(graph)), _filename, _type)
}

function exportDxf(_filename, _type) {
  const core = manager.CurCore()
  // 构建网络图几何信息数据
  const graph = core.exportGraphDatas(true)

  if (!graph) {
    // layer.alert('生成通风网络数据失败!', { skin: 'layui-layer-moon' })
    MessageBox.alert('提取通风网络图几何数据失败!', {
      confirmButtonText: '确定',
      showClose: false
    })
    return
  }

  // ajax请求: 生成dxf文件
  // console.log(graph)
  makeDxf({ graph })
    .then(res => {
      // 关闭loading遮罩
      Loading.Close()
      // 显示文件下载对话框
      downloadFile(stringToBlob(res), _filename, _type)
    })
    .catch(err => {
      // 关闭loading遮罩
      Loading.Close()
      // 弹框显示错误信息
      MessageBox.alert(err, '提示', {
        confirmButtonText: '确定',
        showClose: false
      })
    })
}

function exportTxt(_filename, _type) {
  const core = manager.CurCore()
  const graph = core.exportTopology()
  if (graph == null) {
    // layer.alert('生成通风网络拓扑数据失败!', { skin: 'layui-layer-moon' })
    return
  }
  // console.log(graph)
  // 利用js生成字符串(效率可能不高!)
  const datas = []
  for (var i in graph['edges']) {
    var obj = graph['edges'][i]
    var s = [obj.id, obj.s, obj.t, obj.r, obj.q]
    datas.push(s.join('\t'))
  }
  downloadFile(stringToBlob(datas.join('\n')), _filename, _type)
}

// 生成png图片
// file:///D:/develop/GitTest/GoJS/intro/makingImages.html
function ExportGraph() {
  const core = manager.CurCore()
  const diagram = core.GetDiagram()

  DialogUtil.Show('GraphExportDialog').then(res => {
    if (res) {
      const { name, type, scale } = res
      if (!name) {
        MessageBox.alert('请指定导出图形名称', '提示', {
          confirmButtonText: '确定',
          showClose: false
        })
      } else {
        if (diagram.model.linkDataArray.length === 0) {
          // layer.alert('分支个数为0,无数据可以导出!', {
          //   skin: 'layui-layer-moon'
          // })
        } else if (type === 'svg') {
          exportSvg(scale, name, type)
        } else if (type === 'png' || type === 'jpeg') {
          exportImg(scale, name, type)
        } else if (type === 'dxf') {
          exportDxf(name, type)
        } else if (type === 'txt') {
          exportTxt(name, type)
        }
      }
    }
  })
}

function AutoLayout() {
  const core = manager.CurCore()
  // const diagram = core.GetDiagram()

  DialogUtil.Show('LayoutConfigDialog').then(res => {
    if (res) {
      // 更新config
      config.layout.nodesep = res.nodesep
      config.layout.ranksep = res.ranksep
      config.layout.rankdir = res.rankdir
      config.layout.splines = res.splines

      // 构建网络图几何信息数据
      const graph = core.exportGraphDatas(false)
      if (!graph) {
        // layer.alert('生成通风网络数据失败!', { skin: 'layui-layer-moon' })
        MessageBox.alert('提取通风网络图几何数据失败!', {
          confirmButtonText: '确定',
          showClose: false
        })
        return
      }

      // 构造表单数据
      // res是json对象,包含自动布局的所有数据
      // console.log('自动布局对话框返回:', res)
      // const formData = new FormData()
      // for (const key in res) {
      //   formData.append(key, res[key])
      // }
      res['graph'] = graph
      // formData.append('graph', graph)

      // 显示loading遮罩
      Loading.Show('正在进行自动布局计算, 请耐心等待~')
      // ajax请求: 解析上传的图数据
      parseGraph(res)
        .then(data => {
          // console.log('返回数据:', data)
          // 根据计算的结果更新diagram
          core.updateNetwork(data)
          // 缩放到适合的比例尺
          core.zoomFit()
          // 关闭loading遮罩
          Loading.Close()
        })
        .catch(err => {
          // 关闭loading遮罩
          Loading.Close()
          // 弹框显示错误信息
          MessageBox.alert(err, '提示', {
            confirmButtonText: '确定',
            showClose: false
          })
        })
    }
  })
}

function ConfigGraph() {
  // DialogUtil.Show('UiConfigDialog', { width: 400, height: 300 })
  DialogUtil.Show('SysConfigDialog').then(res => {
    // 更新config
    config.document.name = res.name
    config.document.author = res.author
    config.document.date = res.date
    config.document.comment = res.comment
    config.node.size[0] = res.nodewidth
    config.node.size[1] = res.nodeheight
    config.node.style.fontSize = res.fontsize
  })
}

// function ShowEdgeList() {
//   DialogUtil.Show('EdgeList', {
//     parts: VngUtil.Entity.FindByType('Link')
//   }).then(res => {
//     console.log(res)
//   })
// }

function DrawPointer() {
  const core = manager.CurCore()
  core.setMode('pointer', 'pointer')
}

function DrawNode() {
  const core = manager.CurCore()
  core.setMode('node', 'node')
}

function DrawLink() {
  const core = manager.CurCore()
  core.setMode('link', 'line')
}

// 批量修改选中分支的形状
function SetSelectedLinkCategory(category) {
  const core = manager.CurCore()
  core.setLinkCategory(core.getSelectedLinks(), category)
  core.update()
}

function ReverseSelectedLink() {
  const core = manager.CurCore()
  const links = core.getSelectedLinks()
  if (!links) {
    MessageBox.alert('请至少选择一条分支!', '提示', {
      confirmButtonText: '确定'
    })
  } else {
    core.reverseLinks(links)
  }
}

function UpdateSecondLabel(field) {
  const core = manager.CurCore()
  // 更新所有分支第2个文本标签的内容
  core.updateSecondLabel(core.getAllLinks(), field)
}

function ZoomFit() {
  const core = manager.CurCore()
  core.zoomFit()
}

function ZoomToLink(key) {
  const core = manager.CurCore()
  core.zoomTo('Link', key)
}

function ZoomToNode(key) {
  const core = manager.CurCore()
  core.zoomTo('Node', key)
}

function ResizeDiagram({ width, height }) {
  const core = manager.CurCore()
  core.resize(width, height)
}

function Group() {
  const core = manager.CurCore()
  if (core.getSelectionCount() === 0) {
    MessageBox.alert('请至少选择2个节点成组!', '提示', {
      confirmButtonText: '确定'
    })
  } else {
    core.group()
  }
}

function UnGroup() {
  const core = manager.CurCore()
  if (core.getSelectionCount() === 0) {
    MessageBox.alert('请选择1个组进行解组操作!', '提示', {
      confirmButtonText: '确定'
    })
  } else {
    core.unGroup()
  }
}

function Undo() {
  const core = manager.CurCore()
  core.undo()
}

function Redo() {
  const core = manager.CurCore()
  core.redo()
}

function Copy() {
  const core = manager.CurCore()
  if (core.getSelectionCount() === 0) {
    MessageBox.alert('请至少选择1个图形进行操作!', '提示', {
      confirmButtonText: '确定'
    })
  } else {
    core.copy()
  }
}

function Cut() {
  const core = manager.CurCore()
  if (core.getSelectionCount() === 0) {
    MessageBox.alert('请至少选择1个图形进行操作!', '提示', {
      confirmButtonText: '确定'
    })
  } else {
    core.cut()
  }
}

function Paste() {
  const core = manager.CurCore()
  core.paste()
}

function Delete() {
  const core = manager.CurCore()
  if (core.getSelectionCount() === 0) {
    MessageBox.alert('请至少选择1个图形进行操作!', '提示', {
      confirmButtonText: '确定'
    })
  } else {
    core.delete()
  }
}

function ClearAll() {
  MessageBox.confirm('确定清空所有节点和分支吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const core = manager.CurCore()
    core.resetModel()
  })
}

function SelectAll() {
  const core = manager.CurCore()
  core.selectAll()
}

function PlayAnimation() {
  const core = manager.CurCore()
  // 播放动画
  core.playAnimation()
}

function FilterSelection(type) {
  const core = manager.CurCore()
  core.selectParts(core.currentSelect(), type, true)
}

export default {
  NewGraph,
  OpenGraph,
  DeleteGraph,
  SaveGraph,
  ShareGraph,
  ImportGraph,
  ExportGraph,
  AutoLayout,
  ConfigGraph,
  DrawPointer,
  DrawNode,
  DrawLink,
  ReverseSelectedLink,
  SetSelectedLinkCategory,
  UpdateSecondLabel,
  ZoomFit,
  ZoomToLink,
  ZoomToNode,
  ResizeDiagram,
  Undo,
  Redo,
  Group,
  UnGroup,
  Copy,
  Cut,
  Paste,
  Delete,
  ClearAll,
  SelectAll,
  SimpleTest,
  PlayAnimation,
  FilterSelection
}
